﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace Mozlite
{
    /// <summary>
    /// Cookie管理类。
    /// </summary>
    public class Cookies
    {
        private Cookies() { }
        /// <summary>
        /// 获取Cookie实例。
        /// </summary>
        /// <param name="name">Cookie名称。</param>
        /// <returns>返回Cookie实例。</returns>
        public static HttpCookie GetCookie(string name)
        {
            var context = HttpContext.Current;
            if (context != null)
                return context.Request.Cookies[name];
            return null;
        }
        /// <summary>
        /// 获取Cookie值。
        /// </summary>
        /// <typeparam name="T">Cookie值类型。</typeparam>
        /// <param name="name">返回名称。</param>
        /// <param name="defaultValue">默认值。</param>
        /// <returns>返回Cookie的值。</returns>
        public static T GetCookie<T>(string name, T defaultValue = default(T))
        {
            var cookie = GetCookie(name);
            if (cookie == null)
                return defaultValue;
            return cookie.Value.To<T>(defaultValue);
        }
        /// <summary>
        /// 设置Cookie。
        /// </summary>
        /// <param name="cookie">Cookie实例对象。</param>
        public static void SetCookie(HttpCookie cookie)
        {
            var context = HttpContext.Current;
            if (context != null)
                context.Response.SetCookie(cookie);
        }
        /// <summary>
        /// 删除Cookie。
        /// </summary>
        /// <param name="name">Cookie名称。</param>
        public static void DeleteCookie(string name)
        {
            var cookie = GetCookie(name);
            if (cookie != null)
            {
                cookie.Expires = DateTime.Now.AddSeconds(-10);
                HttpContext.Current.Response.SetCookie(cookie);
            }
        }
        /// <summary>
        /// 移除所有Cookie。
        /// </summary>
        public static void Clear()
        {
            var context = HttpContext.Current;
            if (context != null)
                context.Response.Cookies.Clear();
        }
    }
}
